//
//  WYSendRedPacketController.m
//  Boss
//
//  Created by admin on 2018/6/4.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYSendRedPacketController.h"
#import "WYSendPacketHeaderCell.h"
#import "WYRedPacketCountCell.h"
#import "WYRedPacketRangeCell.h"
#import "WYRedSwitchCell.h"
#import "WYLocationRangeController.h"
#import "TZImagePickerController.h"
#import "WYRedDataView.h"
#import "WYLocationCell.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "WYUploadModel.h"
#import "UIImage+WYSaveImage.h"
#import "WYPayController.h"
#import "WXApi.h"
#import "NSDictionary+ExchangeJson.h"
#import "TZPhotoPickerController.h"
#import "TZAssetModel.h"
#import "WYPayAlertTooler.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WYAddImageViewCell.h"
#import "WYWholeCountryCell.h"
#import "WYCanLeadView.h"
#import "WYInsertHistoryController.h"
@interface WYSendRedPacketController ()<UITableViewDelegate,UITableViewDataSource,WYSendPacketHeaderCellDelegate,UIActionSheetDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,WYLocationCellDelegate,WYWholeCountryCellDelegate>
{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
     BOOL _isSelectOriginalPhoto;
    BOOL _isTure;
    BOOL _HideLoc;
    BOOL _isImport;
    dispatch_group_t upLoad;
    
}
@property (nonatomic, strong) TZAlbumModel *model;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSArray *leftArray;
@property (nonatomic,strong) WYSendPacketHeaderCell *headCell;
@property (nonatomic,strong) WYRedPacketCountCell *outLinkCell;

@property (nonatomic,strong) NSArray *nameArray;
@property (nonatomic,strong) UIAlertAction *action;
@property (nonatomic,strong) UIAlertAction *PerAction;
@property (nonatomic,strong) AMapLocationManager *locationManager;
@property (nonatomic,strong)CLLocation *location;
@property (nonatomic,strong)AMapLocationReGeocode *regeocode;
@property (nonatomic,strong) NSString *myAddress;

@property (nonatomic,strong)NSString *province;
@property (nonatomic,strong) NSString *city;
@property (nonatomic,strong) NSString *district;
@property (nonatomic) NSUInteger scope;
@property (nonatomic) NSUInteger tag;
@property (nonatomic,strong)UIButton *sendBtn;
/**
 * 精准投放类型
 */
@property (nonatomic) NSUInteger accurateType;
@property (nonatomic,strong) NSString *vipLevel;
@property (nonatomic,strong) NSString *whoCanName;
@property (nonatomic,strong) UITextField *moneyTextfield;
@property (nonatomic,strong) UITextField *outLinkTextfield;
@property (nonatomic,strong) UITextField *numberTextfield;

/**
 * 红包类型
 */

@property (nonatomic) NSUInteger type;

@property (nonatomic,strong)NSMutableArray *pathArray;
@property (nonatomic,strong)NSMutableArray *urlArray;
@property (nonatomic,assign)BOOL isImageOver;
@property (nonatomic,assign)BOOL isSend;


@property (nonatomic,strong)NSMutableArray *errorPathArray;
@property (nonatomic,strong)NSMutableArray *errorUrlArray;

@property (nonatomic,strong)WYPayController *payVC;

@property (nonatomic,strong)TZImagePickerController *imagePickerVc;
@property (nonatomic,strong)NSString *scopeName;
@property (nonatomic,strong)NSString *formattedAddress;
@property (nonatomic,strong)NSMutableDictionary *dataDict;

@property (nonatomic,assign)CLLocationCoordinate2D location2d;
@property (nonatomic,strong)WYLocationCell *locationCell;
//@property (nonatomic,strong)WYRedSwitchCell *switchCell;
@end

@implementation WYSendRedPacketController
-(NSMutableDictionary *)dataDict
{
    if (!_dataDict) {
        _dataDict = [[NSMutableDictionary alloc]init];
    }
    return _dataDict;
}
-(NSMutableArray *)pathArray
{
    if (!_pathArray) {
        _pathArray = [[NSMutableArray alloc]init];
    }
    return _pathArray;
}
-(NSMutableArray *)urlArray
{
    if (!_urlArray) {
        _urlArray = [[NSMutableArray alloc]init];
    }
    return _urlArray;
}


-(NSArray *)leftArray
{
    if (!_leftArray) {
        _leftArray = @[@[@""],@[@"VIP用户特权"],@[@"红包金额",@"红包个数"],@[@"红包规则",@"发布范围"],@[@"谁可以领",@"外部链接",@""]];
    }
    return _leftArray;
}
-(NSArray *)nameArray
{
    if (!_nameArray) {
        _nameArray = @[@[@""],@[@""],@[@"元",@"个"],@[@"",@"",@""],@[@"",@"",@""]];
    }
    return _nameArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    
    self.scope = 3;
    self.accurateType = 0;
    self.type = 1;
    
    WYUserMessage *usermessage = [WYStoreModule currentUserMessage];
    if (usermessage.vipId.integerValue>0) {
        _isTure = YES;
    }else{
        _isTure = NO;
    }
    [self setupUI];
    _tag=0;
    self.errorUrlArray = [NSMutableArray array];
    self.errorPathArray = [NSMutableArray array];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXPaySucess:) name:@"WXPaySuccess" object:nil];
//     [[NSNotificationCenter defaultCenter] postNotificationName:@"AlipayResult" object:@{@"result":@"resultDic"}];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AliPayResult:) name:@"AlipayResult" object:nil];
    
    upLoad = dispatch_group_create();
    // Do any additional setup after loading the view.
}
-(void)AliPayResult:(NSNotification *)noc
{
    NSDictionary *dic =noc.object[@"result"];
    NSUInteger status = [dic[@"resultStatus"] integerValue];
    if (status==9000) {
        [self toast:@"发布成功"];
        int64_t delayInSeconds = 2.0; // 延迟的时间
        __weak typeof(self)weakSelf = self;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.tabBarController setSelectedIndex:0];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            weakSelf.tabBarController.tabBar.hidden = NO;
        });
    }
}
-(void)WXPaySucess:(NSNotification *)noc
{
    [self toast:@"发布成功"];
    int64_t delayInSeconds = 2.0; // 延迟的时间
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.tabBarController setSelectedIndex:0];
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        weakSelf.tabBarController.tabBar.hidden = NO;
    });
}
-(void)setupUI
{
    self.navigationItem.title = @"发布红包信息";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"导入" style:(UIBarButtonItemStyleDone) target:self action:@selector(insertHistortMessage)];
    [self.view addSubview:self.tableView];
    CGFloat navHeight;
    if (kDevice_Is_iPhoneX) {
        navHeight = 88;
    }else{
        navHeight = 64;
    }
    self.tableView.estimatedRowHeight = 200;
    self.tableView.frame = CGRectMake(0, navHeight, kScreenWidth, kScreenHeight-navHeight);
    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    
    
    [self.tableView registerClass:[WYSendPacketHeaderCell class] forCellReuseIdentifier:@"WYSendPacketHeaderCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYRedPacketCountCell" bundle:nil] forCellReuseIdentifier:@"WYRedPacketCountCell"];
   // addimageView.backgroundColor = [UIColor redColor];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WYRedPacketRangeCell" bundle:nil] forCellReuseIdentifier:@"WYRedPacketRangeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYRedSwitchCell" bundle:nil] forCellReuseIdentifier:@"WYRedSwitchCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYLocationCell" bundle:nil] forCellReuseIdentifier:@"WYLocationCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WYWholeCountryCell" bundle:nil] forCellReuseIdentifier:@"WYWholeCountryCell"];
    
    
    UIView *footerView = [[UIView alloc]init];
    footerView.frame = CGRectMake(0, 0, kScreenWidth, 128);
    UIButton *sendBtn = [[UIButton alloc]init];
    self.sendBtn = sendBtn;
    [footerView addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
        make.centerY.mas_equalTo(footerView);
    }];
    [sendBtn setBackgroundColor:[UIColor hexStringToColor:@"#D8593F" alpha:1.0]];
    self.tableView.tableFooterView =footerView;
    [sendBtn setTitle:@"提交" forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendMessage:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.locationManager = [[AMapLocationManager alloc]init];
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    [self determineYourPosition];
  
}
-(void)determineYourPosition
{
    WEAKSELF
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            [weakSelf determineYourPosition];
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        weakSelf.location = location;
        weakSelf.regeocode = regeocode;
        weakSelf.province = regeocode.province;
        weakSelf.city = regeocode.city;
        weakSelf.district = regeocode.district;
        [weakSelf.tableView reloadData];
        NSLog(@"location:%@", location);
        
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
        }
        
    }];
}




-(void)insertHistortMessage
{
    WEAKSELF
    WYInsertHistoryController *ihc = [[WYInsertHistoryController alloc]init];
    ihc.complte = ^(WYMYDynamic *errorMessage) {
        weakSelf.isImageOver = YES;
        self->_isImport = YES;
        weakSelf.headCell.inputView.text = errorMessage.content;
        [weakSelf.urlArray addObjectsFromArray:[errorMessage.url componentsSeparatedByString:@","]];
        [self->_selectedPhotos addObjectsFromArray:[errorMessage.url componentsSeparatedByString:@","]];
        [self.dataDict setValue:errorMessage.outLink forKey:[NSString stringWithFormat:@"%ld%ld",4,1]];
        weakSelf.outLinkCell.textField.text =errorMessage.outLink;
        [weakSelf.headCell setImageArray:self->_selectedPhotos];
    };
    [self.navigationController pushViewController:ihc animated:YES];
}





-(void)sendMessage:(UIButton *)btn
{
   
    if (!self.headCell.inputView.text.length) {
        [self toast:@"请输入描述内容"]; return;
    }
    if (!self.moneyTextfield.text.length) {
        [self toast:@"请输入红包金额"]; return;
    }
    if (!self.numberTextfield.text.length) {
        [self toast:@"请输入红包个数"]; return;
    }
    if (self.moneyTextfield.text.floatValue/self.numberTextfield.text.floatValue<0.1) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"单个红包金额不可低于0.1元，请重新选择金额" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    
    
    
    
    
    
    
    if (self.scope==5&&self.moneyTextfield.text.floatValue<100) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"全国红包金额不能低于100元" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];return;
    }
    
    if (self.vipLevel.integerValue==10&&self.moneyTextfield.text.floatValue/self.numberTextfield.text.floatValue<0.5) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"单个白银红包金额不可低于0.5元，请重新选择金额" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];return;
    }
    if (self.vipLevel.integerValue==20&&self.moneyTextfield.text.floatValue/self.numberTextfield.text.floatValue<0.8) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"单个黄金红包金额不可低于0.8元，请重新选择金额" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];return;
    }
    if (self.vipLevel.integerValue==30&&self.moneyTextfield.text.floatValue/self.numberTextfield.text.floatValue<1.0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"单个钻石红包金额不可低于1.0元，请重新选择金额" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];return;
    }
    
    
    
    
    
    
    [self showLoading:@""];
    if (self.urlArray.count&&!self.isImageOver) {
        self.isSend = YES;
        return;
    }
    WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
    if (userMessage.vipId.intValue==0&&_isTure) {
        _isTure = NO;
        self.outLinkTextfield.text = @"";
         [self.dataDict setValue:@"" forKey:[NSString stringWithFormat:@"%ld%ld",4,1]];
        self.accurateType = 0;
        self.vipLevel = @"0";
        [self.tableView reloadData];
        [self toast:@"您还不是会员，成为会员后才可享用VIP特权哦～"];return;
    }
    
    [self hideLoading];
  
    if (!self.payVC) {
        WYPayController *pvc = [[WYPayController alloc]init];
        self.payVC = pvc;
        [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
        [[UIApplication sharedApplication].keyWindow addSubview:pvc.view];
        pvc.view.frame = CGRectMake(0, kScreenHeight-370, kScreenWidth, 370);
        pvc.view.backgroundColor = [UIColor whiteColor];
        WEAKSELF
        pvc.exit = ^(NSString *name) {
            [weakSelf.payVC.view removeFromSuperview];
            [weakSelf setPayVC:nil];
            [weakSelf.maskView removeFromSuperview];
        };
        pvc.complete = ^(NSString *name, NSString *value) {
            [weakSelf.payVC.view removeFromSuperview];
            [weakSelf setPayVC:nil];
            [weakSelf.maskView removeFromSuperview];
            [weakSelf sendRedPacketWithPayType:name];
            //[weakSelf showLoading:@""];
        };
        [pvc setMoney:self.moneyTextfield.text];
    }
}
-(void)sendRedPacketWithPayType:(NSString *)payType
{
    NSString *cor;
    if (self.location2d.latitude&&self.location2d.longitude) {
        cor = [NSString stringWithFormat:@"%f,%f",self.location2d.latitude,self.location2d.longitude];
    }else{
        cor = [NSString stringWithFormat:@"%f,%f",self.location.coordinate.latitude,self.location.coordinate.longitude];
    }
  NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    for (NSObject *model in self.urlArray) {
        
        if ([model isKindOfClass:[WYUploadModel class]]) {
            WYUploadModel *upModel = (WYUploadModel *)model;
             [imageArray addObject:upModel.visitUrl];
        }
        if ([model isKindOfClass:[NSString class]]) {
            NSString *strModel = (NSString *)model;
            [imageArray addObject:strModel];
        }
       
    }
    NSString *address;
    
    if (self.formattedAddress.length) {
        
        if (self.scope==2||self.scope==1) {
            address = [NSString stringWithFormat:@"%@·%@",self.district,self.formattedAddress];
        }else{
            address = [NSString stringWithFormat:@"%@·%@",self.city,self.formattedAddress];
        }
    }else{
        if (self.location) {
            if (self.scope==2||self.scope==1) {
                address =[NSString stringWithFormat:@"%@·%@%@",self.regeocode.district,self.regeocode.street,self.regeocode.number];
            }else{
                address =[NSString stringWithFormat:@"%@·%@%@",self.regeocode.city,self.regeocode.street,self.regeocode.number];
            }
        }
    }
    
    
    WEAKSELF
    [WYHttpServer sendRedPacketWithImages:imageArray WithContent:self.headCell.inputView.text WithOutLink:self.outLinkTextfield.text WithMoney:self.moneyTextfield.text WithNumber:self.numberTextfield.text WithType:@(self.type) WithScope:@(self.scope) WithAccurateType:@(self.accurateType) WithCoordinate:cor WithProvince:self.province WithCity:self.city WithCountry:self.district WithAddress:address WithPayType:payType WithHideLoc:@(_HideLoc) WithVipLevel:self.vipLevel SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
           // NSLog(@"\n\n\n\n\n\n 发布成功");
            if ([payType isEqualToString:@"2"]) {
                NSString *jsonStr = response[@"result"];
                NSDictionary *dic = [NSDictionary dictionaryWithJsonString:jsonStr];
                [weakSelf goToWechat:dic];
            }
            if ([payType isEqualToString:@"1"]) {
                NSString *orderString = response[@"result"];
                [weakSelf gotoAliPay:orderString];
            }
            if ([payType isEqualToString:@"3"]) {
                [weakSelf showSucess];
            }
            
        }else{
            if ([payType isEqualToString:@"3"]) {
                [weakSelf showErrorWithString:errorMessage];
            }else{
                [weakSelf toast:errorMessage];
            }
            //[self hideLoading];
        }
    }];
}
-(void)gotoAliPay:(NSString *)orderString
{
    NSLog(@"%@",orderString);
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:@"BOSS" callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
}
    
-(void)goToWechat:(NSDictionary *)wechatPayDic
{
    PayReq *req = [[PayReq alloc] init];
    req.openID = [wechatPayDic objectForKey:@"appid"];
    req.partnerId = [wechatPayDic objectForKey:@"partnerid"];
    req.prepayId = [wechatPayDic objectForKey:@"prepayid"];
   // req.package = @"WXpay";
    req.package = [wechatPayDic objectForKey:@"package"];
    req.nonceStr = [wechatPayDic objectForKey:@"noncestr"];
    req.timeStamp = [[wechatPayDic objectForKey:@"timestamp"] intValue];
    req.sign = [wechatPayDic objectForKey:@"sign"];
    [WXApi sendReq:req];
}
-(void)showSucess
{
    WEAKSELF
    [[WYPayAlertTooler sharedInstance] showAlertTitle:@"付款成功啦" message:@"" imageName:@"pay_success_icon" btnTitles:@"我知道了" btnClicked:^(NSInteger index) {
        NSLog(@"%ld",index);
        
       // self.hidesBottomBarWhenPushed=NO;
//        self.tabBarController.selectedIndex=0;
        
        [weakSelf.tabBarController setSelectedIndex:0];
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        weakSelf.tabBarController.tabBar.hidden = NO;
       
       
    }];
}
-(void)showErrorWithString:(NSString *)str
{
    [[WYPayAlertTooler sharedInstance] showAlertTitle:str message:@"支付遇到问题，请尝试重新支付" imageName:@"pay_error_icon" btnTitles:@[@"放弃",@"重新支付"] btnClicked:^(NSInteger index) {
        NSLog(@"%ld",index);
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isTure) {
         return 5;
    }else{
         return 4;
    }
   
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }
    if (section==1) {
        return 1;
    }
    if (section==2) {
        return 2;
    }
    if (section==3) {
        return 2;
    }
    if (section==4) {
        return 2;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *leftName = self.leftArray[indexPath.section][indexPath.row];
    NSString *rightName = self.nameArray[indexPath.section][indexPath.row];
    
    if (indexPath.section ==0) {
        WYSendPacketHeaderCell *cell  =[tableView dequeueReusableCellWithIdentifier:@"WYSendPacketHeaderCell" forIndexPath:indexPath];
        self.headCell = cell;
        cell.delegate = self;
        cell.selfVc = self;
        if (!cell) {
            cell = [[WYSendPacketHeaderCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"WYSendPacketHeaderCell"];
        }
        /// [cell.inputView becomeFirstResponder];
        
        [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
        
        return cell;
    }
    if (indexPath.section==2) {
        WYRedPacketCountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedPacketCountCell" forIndexPath:indexPath];
        
        if (!cell ) {
            cell =[[NSBundle mainBundle] loadNibNamed:@"WYRedPacketCountCell" owner:nil options:nil].firstObject;
        }
        cell.leftLabel.text = leftName;
        cell.rightLabel.text = rightName;
        [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
        
        if (indexPath.row==0) {
            
            cell.saveData = ^(NSString *text) {
                [self.dataDict setValue:text forKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            };
            NSArray *indexArray = [self.dataDict allKeys];
            if ([indexArray containsObject:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]]) {
                cell.textField.text = [self.dataDict objectForKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            }else{
                cell.textField.text = nil;
            }
            cell.textField.placeholder = @"请输入总金额";
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            self.moneyTextfield = cell.textField;
        }else{
            cell.saveData = ^(NSString *text) {
                [self.dataDict setValue:text forKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            };
            NSArray *indexArray = [self.dataDict allKeys];
            if ([indexArray containsObject:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]]) {
                cell.textField.text = [self.dataDict objectForKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            }else{
                cell.textField.text = nil;
            }
            cell.textField.placeholder = @"请输入红包个数";
            self.numberTextfield = cell.textField;
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
        }
        return cell;
    }
    if (indexPath.section==3) {
        if (indexPath.row==0) {
            WYRedPacketRangeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedPacketRangeCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"WYRedPacketRangeCell" owner:nil options:nil].firstObject;
            }
            cell.leftLabel.text = leftName;
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            cell.rightLabel.text = @"拼手气红包";
            return cell;
        }else
//        if(indexPath.row==1){
//
//            WYRedPacketCountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedPacketCountCell" forIndexPath:indexPath];
//            if (!cell ) {
//                cell =[[NSBundle mainBundle] loadNibNamed:@"WYRedPacketCountCell" owner:nil options:nil].firstObject;
//            }
//            cell.leftLabel.text = leftName;
//            cell.rightLabel.text=@"";
//            cell.textField.placeholder = @"链接地址";
//            cell.textField.keyboardType = UIKeyboardTypeDefault;
//            self.outLinkTextfield = cell.textField;
//            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
//            cell.saveData = ^(NSString *text) {
//                [self.dataDict setValue:text forKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
//            };
//            NSArray *indexArray = [self.dataDict allKeys];
//            if ([indexArray containsObject:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]]) {
//                cell.textField.text = [self.dataDict objectForKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
//            }else{
//                cell.textField.text = nil;
//            }
//            return cell;
//        }else
        {
            WYLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYLocationCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"WYLocationCell" owner:nil options:nil].firstObject;
            }
            self.locationCell = cell;
            cell.delegate = self;
            cell.leftLabel.text = leftName;
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            if (self.scopeName.length) {
                cell.rightLabel.text = self.scopeName;
            }else{
                cell.rightLabel.text = @"全市";
            }
            if (self.formattedAddress.length) {
                
                if (self.scope==2||self.scope==1) {
                     cell.locationLabel.text = [NSString stringWithFormat:@"%@·%@",self.district,self.formattedAddress];
                }else{
                    cell.locationLabel.text = [NSString stringWithFormat:@"%@·%@",self.city,self.formattedAddress];
                }
                
                
               
            }else{
                if (self.location) {
                    if (self.scope==2||self.scope==1) {
                        cell.locationLabel.text =[NSString stringWithFormat:@"%@·%@%@",self.regeocode.district,self.regeocode.street,self.regeocode.number];
                    }else{
                       cell.locationLabel.text =[NSString stringWithFormat:@"%@·%@%@",self.regeocode.city,self.regeocode.street,self.regeocode.number];
                    }
                }
            }
             return cell;
        }
       
    }
    
    if (indexPath.section==1) {
        WYRedSwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedSwitchCell" forIndexPath:indexPath];
        if (!cell) {
            cell =[[NSBundle mainBundle]loadNibNamed:@"WYRedSwitchCell" owner:nil options:nil].firstObject;
        }
        cell.leftLabel.text = leftName;
        [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
        [cell.onSwitch addTarget:self action:@selector(changeTableView:) forControlEvents:(UIControlEventValueChanged)];
        cell.onSwitch.on = _isTure;
        return cell;
    }
    if (indexPath.section==4) {
        if (indexPath.row==0) {
            WYRedPacketRangeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedPacketRangeCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"WYRedPacketRangeCell" owner:nil options:nil].firstObject;
            }
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            cell.leftLabel.text = leftName;
            if (self.whoCanName.length) {
                cell.rightLabel.text = self.whoCanName;
            }else{
                cell.rightLabel.text = @"请选择";
            }
            
            cell.rightLabel.textColor = [UIColor hexStringToColor:@"#222222" alpha:1.0];
            return cell;
        }else if(indexPath.row==2){
            WYWholeCountryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYWholeCountryCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"WYWholeCountryCell" owner:nil options:nil].firstObject;
            }
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            
            WYRedPacketCountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedPacketCountCell" forIndexPath:indexPath];
            if (!cell ) {
                cell =[[NSBundle mainBundle] loadNibNamed:@"WYRedPacketCountCell" owner:nil options:nil].firstObject;
            }
            self.outLinkCell = cell;
            cell.leftLabel.text = leftName;
            cell.rightLabel.text=@"";
            cell.textField.placeholder = @"链接地址";
            cell.textField.keyboardType = UIKeyboardTypeDefault;
            
            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
            cell.saveData = ^(NSString *text) {
                [self.dataDict setValue:text forKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            };
            NSArray *indexArray = [self.dataDict allKeys];
            if ([indexArray containsObject:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]]) {
                cell.textField.text = [self.dataDict objectForKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            }else{
                cell.textField.text = nil;
            }
            self.outLinkTextfield = cell.textField;
            return cell;
            
            
            
            
//            WYRedPacketRangeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRedPacketRangeCell" forIndexPath:indexPath];
//            if (!cell) {
//                cell = [[NSBundle mainBundle]loadNibNamed:@"WYRedPacketRangeCell" owner:nil options:nil].firstObject;
//            }
//            cell.leftLabel.text = leftName;
//            [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
//            if ([self.province isEqualToString:self.city]) {
//                cell.rightLabel.text = [NSString stringWithFormat:@"%@ %@",self.province,self.district];
//            }else{
//               cell.rightLabel.text = [NSString stringWithFormat:@"%@ %@ %@",self.province,self.city,self.district];
//            }
            return cell;
        }
    }
    return nil;
}
-(void)didSelectChageLocationButtonWithCell:(WYLocationCell *)cell
{
    if (_isTure) {
        [self pushToLocationController];
    }else{
        WEAKSELF
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //weakSelf.action = action;
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"三公里" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.scope = 1;
            weakSelf.scopeName = @"三公里";
            weakSelf.locationCell.rightLabel.text = @"三公里";
            [weakSelf judgeLocation];
        }];
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"全区/县" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.scope = 2;
            weakSelf.scopeName = @"全区/县";
            weakSelf.locationCell.rightLabel.text = @"全区/县";
            [weakSelf judgeLocation];
        }];
        UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"全市" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.scope = 3;
            weakSelf.scopeName = @"全市";
            weakSelf.locationCell.rightLabel.text = @"全市";
            [weakSelf judgeLocation];
        }];
        WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
        UIAlertAction *action5 = [UIAlertAction actionWithTitle:@"全国" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (userMessage.vipId.integerValue ==30) {
                weakSelf.scope = 5;
                weakSelf.scopeName = @"全国";
                weakSelf.locationCell.rightLabel.text = @"全国";
                [weakSelf judgeLocation];
            }else{
                [weakSelf diamondsShowToast];
            }
        }];
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController addAction:action3];
        [alertController addAction:action4];
        if (userMessage.vipId.integerValue ==30) {
            [alertController addAction:action5];
        }
        if (IS_IPAD) {
            UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
            popPresenter.sourceView = cell;
            popPresenter.sourceRect = cell.bounds;
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }
    
}
-(void)judgeLocation
{
    
    if (self.formattedAddress.length) {
        
        if (self.scope==2||self.scope==1) {
            self.locationCell.locationLabel.text = [NSString stringWithFormat:@"%@·%@",self.district,self.formattedAddress];
        }else{
            self.locationCell.locationLabel.text = [NSString stringWithFormat:@"%@·%@",self.city,self.formattedAddress];
        }
    }else{
        if (self.location) {
            if (self.scope==2||self.scope==1) {
                self.locationCell.locationLabel.text =[NSString stringWithFormat:@"%@·%@%@",self.regeocode.district,self.regeocode.street,self.regeocode.number];
            }else{
                self.locationCell.locationLabel.text =[NSString stringWithFormat:@"%@·%@%@",self.regeocode.city,self.regeocode.street,self.regeocode.number];
            }
        }
    }
}


-(void)didHideButtonWithState:(BOOL)state
{
    _HideLoc = state;
}

-(void)didSelectChageWholeCountryButtonWithCell:(WYWholeCountryCell *)cell WithBtnState:(BOOL)state
{
    if (state) {
        self.scopeName = @"全国";
        self.locationCell.rightLabel.text = @"全国";
        self.scope = 5;
    }else{
        self.scope = 3;
        self.scopeName = @"全市";
        self.locationCell.rightLabel.text = @"全市";
    }
}
-(void)diamondsShowToast
{
     [self toast:@"钻石会员用户才有权发放\n全国范围红包信息哦~"];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==3&&indexPath.row==0) {
        WEAKSELF
        WYRedPacketRangeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //weakSelf.action = action;
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"等额红包" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //        [action setValue:[UIColor greenColor] forKey:@"_titleTextColor"];
            weakSelf.action = action;
            cell.rightLabel.text = action.title;
            weakSelf.type = 2;
        }];
        
        if ([action2.title isEqualToString:self.action.title]) {
            [action2 setValue:kColorMainColor forKey:@"_titleTextColor"];
        }
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"拼手气红包" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.action = action;
             cell.rightLabel.text = action.title;
            weakSelf.type = 1;
        }];
        if ([action3.title isEqualToString:self.action.title]) {
            [action3 setValue:kColorMainColor forKey:@"_titleTextColor"];
        }
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController addAction:action3];
        
        if (IS_IPAD) {
            UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
            popPresenter.sourceView = cell;
            popPresenter.sourceRect = cell.bounds;
            [self presentViewController:alertController animated:YES completion:nil];
            
        }else{
             [self presentViewController:alertController animated:YES completion:nil];
        }
    }
    if (indexPath.section==4) {
//        WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
//        if (!userMessage.vipId.integerValue) {
//            [self toast:@"这是会员专属特权哦"]; return;
//        }
        if (indexPath.row==0) {
            WYRedPacketRangeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            WEAKSELF
            [WYCanLeadView showWhoCanView:@"" CanBlock:^(NSString *name, NSString *accurateType,NSString *vipLevel) {
                weakSelf.accurateType = accurateType.integerValue;
                weakSelf.vipLevel = vipLevel;
                cell.rightLabel.text = name;
                NSLog(@"name =%@ accurateType =%@ vipLevel= %@",name,accurateType,vipLevel);
            }];
        }
        if (indexPath.row==1) {
            [self pushToLocationController];
        }
    }
}
-(void)pushToLocationController
{
    
    WYLocationRangeController *loc = [[WYLocationRangeController alloc]init];
    WEAKSELF
    loc.locationBlock = ^(CLLocationCoordinate2D location) {
        weakSelf.location2d = location;
    };
    loc.lastLoction = self.location2d;
    loc.complete = ^(NSString *address, NSString *value, NSUInteger scope) {
        weakSelf.scope = scope;
        weakSelf.scopeName = value;
        [weakSelf.tableView reloadData];
    };
    loc.address = ^(NSString *province, NSString *city, NSString *district,NSString *formattedAddress) {
        weakSelf.province = province;
        weakSelf.city = city;
        weakSelf.district= district;
        weakSelf.formattedAddress = formattedAddress;
        [weakSelf.tableView reloadData];
    };
    
    [self.navigationController pushViewController:loc animated:YES];
    
}


#pragma mark - WYSendPacketHeaderCellDelegate
-(void)didChangeHeight:(WYSendPacketHeaderCell *)cell
{
    [self.tableView reloadData];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
   // [cell.inputView becomeFirstResponder];
}
-(void)didSelectCollectionViewWithIndex:(NSIndexPath *)indexPath WithCell:(WYAddImageViewCell *)cell
{
    
    //WEAKSELF
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    WEAKSELF
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
 
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushTZImagePickerController];
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    if (IS_IPAD) {
        UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
        popPresenter.sourceView = cell;
        popPresenter.sourceRect = cell.bounds;
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark TZIm
#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    
    TZImagePickerController *imagePickerVc;
    if (_isImport) {
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9-_selectedPhotos.count columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    }else{
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    }
    
    // imagePickerVc.navigationBar.translucent = NO;
    self.imagePickerVc = imagePickerVc;
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    
//    if (self.maxCountTF.text.integerValue > 1) {
        // 1.设置目前已经选中的图片数组
    if (!_isImport) {
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    
//    }
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];

    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo =NO;
    imagePickerVc.allowPickingImage =YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.allowPickingMultipleVideo =NO; // 是否可以多选视频
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    imagePickerVc.showSelectedIndex =YES;
#pragma mark - 到这里为止
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}


#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
     TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    
    [[TZImageManager manager] savePhotoWithImage:photo location:self.location completion:^(NSError *error){
        if (error) {
            [tzImagePickerVc hideProgressHUD];
            NSLog(@"图片保存失败 %@",error);
        } else {
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                  
                    [self refreshCollectionViewWithAddedAsset:assetModel.asset image:photo];
                    [self uploadImageToService];
                }];
            }];
        }
    }];
}
- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    [_selectedAssets addObject:asset];
    [_selectedPhotos addObject:image];
    [self.headCell setImageArray:_selectedPhotos];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    
    
    
    
    if (_isImport) {
        [_selectedAssets addObjectsFromArray:assets];
        [_selectedPhotos addObjectsFromArray:photos];
    }else{
        _selectedAssets = [NSMutableArray arrayWithArray:assets];
        _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    }
    
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [self.headCell setImageArray:_selectedPhotos];
    [self uploadImageToService];
    
}
-(void)uploadImageToService
{
    for (int i=0; i<_selectedPhotos.count; i++) {
        WEAKSELF
        if ([_selectedPhotos[i] isKindOfClass:[NSString class]]) {
            continue;
        }
        UIImage *image =  _selectedPhotos[i];
        NSString *path = [image QCloudTempFilePathWithExtension:@"PNG" WithCount:[NSString stringWithFormat:@"%d",i]];
      BOOL error = [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
        if (error) {
            if (!_isImport) {
                [weakSelf.urlArray removeAllObjects];
            }
            
            [WYHttpServer uploadImageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
                WYUploadModel *model = [WYUploadModel getupLoadModelFromJson:response[@"result"]];
                [weakSelf.urlArray addObject:model];
                [weakSelf uploadToTecentServiceWithUrl:model.uploadUrl WithPath:path];
            }];
        }
    }
}

-(void)uploadToTecentServiceWithUrl:(NSString *)url WithPath:(NSString *)path
{
    
     dispatch_group_enter(upLoad);
    [WYHttpServer PUTWithURLStr:url filePath:path SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        dispatch_group_leave(self->upLoad);
        //NSLog(@"%@--\n",model.visitUrl);
        if (success) {
            
        }else{
            
        }
    }];
    WEAKSELF
    dispatch_group_notify(upLoad, dispatch_get_main_queue(), ^{
        weakSelf.isImageOver = YES;
//        [weakSelf.headCell setImageArray:weakSelf.urlArray];
        if (weakSelf.isSend) {
            [weakSelf sendMessage:weakSelf.sendBtn];
        }
        
    });
}
-(void)deleteImageClick:(NSUInteger)inter
{
    [_selectedPhotos removeObjectAtIndex:inter];
    if (!_isImport) {
         [_selectedAssets removeObjectAtIndex:inter];
    }
   
    [self.urlArray removeObjectAtIndex:inter];
    [self.headCell setImageArray:_selectedPhotos];
}
// If user picking a video, this callback will be called.
// If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
// 如果用户选择了一个视频，下面的handle会被执行
// 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    // open this code to send video / 打开这段代码发送视频
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPreset640x480 success:^(NSString *outputPath) {
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
   // [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

// If user picking a gif image, this callback will be called.
// 如果用户选择了一个gif图片，下面的handle会被执行
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
   // [_collectionView reloadData];
}

// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    return YES;
}

-(void)changeTableView:(UISwitch *)btn
{
    btn.on = !btn.isOn;
    _isTure = btn.on;
    [self.tableView reloadData];
}


@end
